﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace TemplateLibraryConnector
{
    [Serializable]
    public sealed class TemplateLibraryConnectorSettings
    {
        [NonSerialized] private const string PROPERTY_KEY = "GREP_TLC_SETTINGS";
        [NonSerialized] private const string TemplateLibraryHubUrlKey = "TemplateLibraryConnector.HubUrl";

        public static TemplateLibraryConnectorSettings Default
        {
            get
            {
                return new TemplateLibraryConnectorSettings
                           {
                               DescriptionFieldName = "Description",
                               TemplateListIds = "",
                               WebIds = ""
                           };
            }
        }

        private static SPWebApplication WebApplication
        {
            get { return SPContext.Current.Site.WebApplication; }
        }



        public string GetTemplateHubAddress(string defaultHubaddress)
        {
            return RetrieveTextProperty(TemplateLibraryHubUrlKey, defaultHubaddress);
        }

        public string DescriptionFieldName { get; set; }
        public bool Enabled { get; set; }
        public string TemplateListIds { get; set; }
        public string WebIds { get; set; }

        public static TemplateLibraryConnectorSettings LoadFromList(SPList list)
        {
            if (!list.RootFolder.Properties.ContainsKey(PROPERTY_KEY))
            {
                return null;
            }
            var settings =
                TinyXmlSerializer.Deserialize<TemplateLibraryConnectorSettings>(
                    list.RootFolder.Properties[PROPERTY_KEY] as string);
            return settings;
        }

        /// <summary>
        /// Saves the settings to the SPList (e.g. library), in its property bag
        /// </summary>
        /// <param name="list"></param>
        /// <param name="settings"></param>
        public static void SaveToList(SPList list, TemplateLibraryConnectorSettings settings)
        {
            list.RootFolder.Properties[PROPERTY_KEY] = TinyXmlSerializer.Serialize(settings);
            list.RootFolder.Update();
        }


        private static string RetrieveTextProperty(string key, string defaultValue)
        {
            string returnValue = defaultValue;
            if (WebApplication.Properties.ContainsKey(key))
            {
                string value = WebApplication.Properties[key].ToString();
                if (!string.IsNullOrEmpty(value))
                    returnValue = value;
            }
            return returnValue;
        }
    }
}